package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    // 收货地址
    @Override
    public List<Address> list() {
        //构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());//用户id

        //查询地址铺
        return addressMapper.selectList(qw);
    }

    //新增地址
    @Override
    public void save(Address address) {
        //补全信息
        address.setUserId(UserHolder.get().getId());//用户id
        address.setIsDefault(0);//非默认地址

        //mapper新增
        addressMapper.insert(address);
    }

    //设置默认地址
    @Override
    public void setDefault(Long id) {
        //1.把当前用户所有收货地址设置为非默认
        // 1-1 设置修改内容
        Address address1 = new Address();
        address1.setIsDefault(0);
        //1-2设置用户id为条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        //1-3更新
        addressMapper.update(address1,qw);

        //将当前收货地址设置为默认
        Address address2 = new Address();
        address2.setId(id);//收获地址
        address2.setIsDefault(1);//默认
        addressMapper.updateById(address2);
    }

    // 去结算（查询默认收货地址
    @Override
    public Address findDefault() {
        //1.构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault,1);//默认值=1
        qw.eq(Address::getUserId,UserHolder.get().getId());//用户id

        //2.调用mapper
        return addressMapper.selectOne(qw);
    }

    //地址回显
    @Override
    public Address  findByIdAddress(Long id) {
        //调用mapper修改
        return addressMapper.selectById(id);
    }

    //修改地址
    @Override
    public void updateByAddress(Address address) {
        //修改原来信息
        addressMapper.updateById(address);
    }

    //删除地址
    @Override
    public void deleteByAddress(Long ids) {
        //调用方法删除
        addressMapper.deleteById(ids);

    }
}
